// backend/src/services/device/deviceManager.js
const Device = require('../../models/device');
const logger = require('../../utils/logger');
const redis = require('../../utils/redis');

class DeviceManager {
    constructor() {
        this.activeDevices = new Map();
    }

    async registerDevice(deviceInfo) {
        try {
            const { deviceId, type, ip } = deviceInfo;

            // 创建或更新设备信息
            const device = await Device.findOneAndUpdate(
                { deviceId },
                {
                    $set: {
                        type,
                        'configuration.ip': ip,
                        'status.lastSeen': new Date()
                    }
                },
                { upsert: true, new: true }
            );

            // 缓存设备状态
            await redis.set(`device:${deviceId}:status`, JSON.stringify({
                connected: false,
                lastSeen: new Date(),
                configuration: device.configuration
            }));

            return device;
        } catch (error) {
            logger.error('Device registration error:', error);
            throw error;
        }
    }

    async connectDevice(deviceId, websocket) {
        try {
            const device = await Device.findOne({ deviceId });
            if (!device) {
                throw new Error('Device not found');
            }

            this.activeDevices.set(deviceId, {
                websocket,
                connectedAt: new Date(),
                device
            });

            await Device.updateOne(
                { deviceId },
                {
                    'status.connected': true,
                    'status.lastSeen': new Date()
                }
            );

            logger.info(`Device ${deviceId} connected`);
            return device;
        } catch (error) {
            logger.error(`Error connecting device ${deviceId}:`, error);
            throw error;
        }
    }

    getDeviceConnection(deviceId) {
        return this.activeDevices.get(deviceId);
    }

    async disconnectDevice(deviceId) {
        try {
            const connection = this.activeDevices.get(deviceId);
            if (connection) {
                connection.websocket.close();
                this.activeDevices.delete(deviceId);
            }

            await Device.updateOne(
                { deviceId },
                { 'status.connected': false }
            );

            logger.info(`Device ${deviceId} disconnected`);
        } catch (error) {
            logger.error(`Error disconnecting device ${deviceId}:`, error);
        }
    }

    async getDeviceStatus(deviceId) {
        try {
            const cachedStatus = await redis.get(`device:${deviceId}:status`);
            if (cachedStatus) {
                return JSON.parse(cachedStatus);
            }
            return null;
        } catch (error) {
            logger.error(`Error getting device status for ${deviceId}:`, error);
            throw error;
        }
    }
}

module.exports = new DeviceManager();
